package com.asimplefox.controllers;

import com.asimplefox.configs.FileConfig;
import com.asimplefox.entity.Articles;
import com.asimplefox.service.IArticlesService;
import com.asimplefox.service.abst.ResultU;
import io.github.kloping.date.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 数据的增删改查
 *
 * @author github kloping
 * @date 2024/11/26-12:59
 */
@Slf4j
@RestController
@RequestMapping("/api/article")
public class ArticleController implements ResultU {

    @RequestMapping("uploadimg")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object uploadImg(@RequestParam("file") MultipartFile multipartFile) {
        FileConfig.FileWithPath ffp = null;
        try {
            ffp = fileConfig.getFileWithPath("articles/content/", String.format("%s.%s", UUID.randomUUID().toString(), "jpg"));
            ffp.write(multipartFile.getBytes());
        } catch (IOException e) {
            log.error("upload image err: {1}", e);
            return fail("图片上传失败");
        }
        return success(ffp.getUrl());
    }

    @Autowired
    IArticlesService articlesService;

    @GetMapping("/get")
    public Object get(@RequestParam("id") Integer id) {
        Object o = articlesService.getById(id);
        return o == null ? fail("未找到") : o;
    }

    @GetMapping("/list")
    public Object list(@RequestParam(value = "ps", defaultValue = "5") Integer pageSize,
                       @RequestParam(value = "pn", defaultValue = "1") Integer pageNum) {
        return articlesService.pageList(pageNum, pageSize);
    }

    @Autowired
    FileConfig fileConfig;

    @PostMapping
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object post(
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("image_url") MultipartFile multipartFile) {
        FileConfig.FileWithPath ffp = null;
        try {
            ffp = fileConfig.getFileWithPath("articles/",
                    String.format("%s/%s", UUID.randomUUID().toString(), "title.png"));
            ffp.write(multipartFile.getBytes());
        } catch (IOException e) {
            log.error("upload image err: {1}", e);
            return fail("图片上传失败");
        }
        Articles articles = new Articles();
        articles.setCreated(String.format("%s-%s-%s", DateUtils.getYear(), DateUtils.getMonth(), DateUtils.getDay()))
                .setContent(content).setTitle(title).setImageUrl(ffp.getUrl());
        if (articlesService.save(articles)) {
            return result(200, "上传成功", "id", articles.getId());
        }
        return fail("上传失败");
    }

    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object delete(@RequestParam("id") Integer id) {
        if (articlesService.removeById(id)) {
            return result(200, "删除成功");
        } else {
            return fail("删除失败");
        }
    }

    @PutMapping
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object put(@RequestParam("id") Integer id,
                      @RequestParam("title") String title,
                      @RequestParam("content") String content,
                      @RequestParam("image_url") MultipartFile multipartFile) {
        Articles articles = articlesService.getById(id);
        if (articles == null) {
            return fail("文章不存在");
        } else {
            if (multipartFile != null && !multipartFile.isEmpty()) {
                fileConfig.delAndDir(articles.getImageUrl());
            }
        }
        FileConfig.FileWithPath ffp = null;
        try {
            ffp = fileConfig.getFileWithPath("articles/",
                    String.format("%s/%s", UUID.randomUUID().toString(), "title.png"));
            ffp.write(multipartFile.getBytes());
        } catch (IOException e) {
            log.error("upload image err: {1}", e);
            return fail("图片上传失败");
        }
        articles = new Articles();
        articles.setImageUrl(ffp.getUrl()).setTitle(title).setContent(content);
        boolean k = articlesService.lambdaUpdate().eq(Articles::getId, id)
                .set(Articles::getTitle, title)
                .set(Articles::getContent, content)
                .set(Articles::getImageUrl, ffp.getUrl())
                .update();
        if (k) {
            return result(200, "更新成功");
        } else return fail("更新异常");
    }
}
